import { Button, Slider, Switch } from 'antd';
import { useEffect, useMemo, useState } from 'react';

import MyModal from '@/components/MyModal';
import QuestionTip from '@/components/tooltip/QuestionTip';
import { t } from '@/locales/i18n';
import { LLMModelItemType } from '@/types/ai/model';
import { SettingAIDataType } from '@/types/app/type';
import { NodeInputKeyEnum } from '@/types/workflow/constant';
import { getWebLLMModel } from '@/utils/system/utils';

import AIModelSelector from '../AIModelSelector';

function AIChatSettingsModal({
  onClose,
  onSuccess,
  defaultData,
  llmModels = [],
}: {
  onClose: () => void;
  onSuccess: (e: SettingAIDataType) => void;
  defaultData: SettingAIDataType;
  llmModels?: LLMModelItemType[];
}) {
  const [refresh, setRefresh] = useState(false);

  const [data, setData] = useState<SettingAIDataType>(defaultData);

  useEffect(() => {
    console.log('defaultData', defaultData);
  }, [defaultData]);

  const model = useMemo(() => {
    return data.model;
  }, [data]);
  const showResponseAnswerText = useMemo(() => data.isResponseAnswerText !== undefined, [data]);
  const showVisionSwitch = useMemo(() => data.aiChatVision !== undefined, [data]);
  const showMaxHistoriesSlider = useMemo(() => data.maxHistories !== undefined, [data]);
  const showEnableReasoning = useMemo(() => data.enableReasoning !== undefined, [data]);
  const useVision = useMemo(() => data.aiChatVision !== undefined, [data]);

  const selectedModel = getWebLLMModel(model);
  const llmSupportVision = !!selectedModel?.vision;

  const tokenLimit = useMemo(() => {
    return selectedModel?.maxResponse || 4096;
  }, [selectedModel?.maxResponse]);

  const onChangeModel = (e: string) => {
    setData((prev) => {
      return {
        ...prev,
        model: e,
      };
    });

    // update max tokens
    const modelData = getWebLLMModel(e);
    if (modelData) {
      setData((prev) => {
        return {
          ...prev,
          maxToken: modelData.maxResponse / 2,
        };
      });
    }

    setRefresh(!refresh);
  };

  const handleSubmit = () => {
    // console.log(data);

    onSuccess(data);
  };

  const labelClass = 'flex items-center text-sm text-gray-900 w-[8rem]';

  const updateData = (key: string, value: any) => {
    setData((prevData) => ({
      ...prevData,
      [key]: value,
    }));
    setRefresh(!refresh);
  };

  return (
    <MyModal
      isOpen
      iconSrc="ic_robot"
      onClose={onClose}
      title={<>{t('core.ai.AI settings')}</>}
      minW="600px"
    >
      <div className="overflow-hidden">
        <div className="flex items-center">
          <div className={`${labelClass} mr-2`}>{t('core.ai.Model')}</div>
          <div className="flex-1">
            <AIModelSelector
              value={data.model}
              options={llmModels.map((item) => ({
                value: item.model,
                label: item.name,
              }))}
              onChange={onChangeModel}
            />
          </div>
        </div>
        <div className="mt-6 flex">
          <div className={`${labelClass} mr-2`}>{t('core.app.Temperature')}</div>
          <div className="ml-1 flex-1">
            <Slider
              marks={{
                0: t('core.app.deterministic'),
                10: t('core.app.Random'),
              }}
              min={0}
              max={10}
              value={data.temperature}
              onChange={(e) => {
                updateData(NodeInputKeyEnum.aiChatTemperature, e);
              }}
              style={{ width: '95%' }}
            />
          </div>
        </div>
        <div className="mt-6 flex">
          <div className={`${labelClass} mr-2`}>{t('core.app.Max tokens')}</div>
          <div className="flex-1">
            <Slider
              marks={{
                100: '100',
                [tokenLimit]: `${tokenLimit}`,
              }}
              min={100}
              max={tokenLimit}
              step={50}
              value={data.maxToken}
              onChange={(val) => {
                updateData(NodeInputKeyEnum.aiChatMaxToken, val);
              }}
              style={{ width: '95%' }}
            />
          </div>
        </div>
        {showEnableReasoning && (
          <div className="mt-6 flex">
            <div className={`${labelClass} mr-2`}>启用推理</div>
            <div className="flex-1">
              <Slider
                marks={{
                  0: '0',
                  30: '30',
                }}
                min={0}
                max={30}
                value={data.maxHistories ?? 6}
                onChange={(e) => {
                  updateData('maxHistories', e);
                }}
                style={{ width: '95%' }}
              />
            </div>
          </div>
        )}

        {showMaxHistoriesSlider && (
          <div className="mt-6 flex">
            <div className={`${labelClass} mr-2`}>{t('core.app.Max histories')}</div>
            <div className="flex-1">
              <Slider
                marks={{
                  0: '0',
                  30: '30',
                }}
                min={0}
                max={30}
                value={data.maxHistories ?? 6}
                onChange={(e) => {
                  updateData('maxHistories', e);
                }}
                style={{ width: '95%' }}
              />
            </div>
          </div>
        )}
        {showResponseAnswerText && (
          <div className="mt-6 flex items-center">
            <div className="flex w-[8rem] items-center text-sm text-gray-900">
              {t('core.app.Ai response')}
              <QuestionTip
                className="ml-1"
                title={t('core.module.template.AI response switch tip')}
              />
            </div>
            <div className="flex-1">
              <Switch
                checked={data.isResponseAnswerText}
                onChange={(value) => {
                  updateData(NodeInputKeyEnum.aiChatIsResponseText, value);
                }}
              />
            </div>
          </div>
        )}
      </div>
      <div className="mt-6 flex justify-end">
        <Button onClick={onClose}>{t('common.Close')}</Button>
        <Button type="primary" className="ml-4" onClick={handleSubmit}>
          {t('common.Confirm')}
        </Button>
      </div>
    </MyModal>
  );
}

export default AIChatSettingsModal;
